#include "str.h"

void str_cpy_base(str *string, const char* new_string, const size_t new_string_len)
{
    size_t string_alloc = str_alloc(*string);

    char *r_string;

    if (new_string_len > string_alloc - 1 || new_string_len < (string_alloc - 1)/4)
    {
        size_t r_string_alloc = str_alloc_size(new_string_len);

        r_string = malloc(2*sizeof(size_t) + r_string_alloc * sizeof(char));

        *((size_t*)r_string) = new_string_len; // r_string len
        *((size_t*)r_string + 1) = r_string_alloc;

        r_string = r_string + 2*sizeof(size_t);

        free((size_t*)(*string) - 2); // free old string
    }
    else
    {
        *((size_t*)(*string) - 2) = new_string_len;

        r_string = *string;
    }

    for (size_t i = 0; i < new_string_len; i++)
        r_string[i] = new_string[i];

    r_string[new_string_len] = '\0';

    *string = r_string;
}

void str_cpy(str *string, const char* new_string)
{
    size_t new_string_len = strlen(new_string);
    
    str_cpy_base(string, new_string, new_string_len);
}

void str_cpy_s(str *string, const str new_string)
{
    size_t new_string_len = str_len(new_string);
    
    str_cpy_base(string, new_string, new_string_len);
}
